package tech.edwardvan.rabbitmqdemo.pattern.simple;

import cn.hutool.core.thread.ThreadUtil;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import tech.edwardvan.rabbitmqdemo.pattern.CommonUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 简单模式-消费者
 *
 * @author EdwardVan
 */
@Slf4j
public class Consumer {


    public static void main(String[] args) throws IOException, TimeoutException {
        //获取一个连接
        Connection connection = CommonUtil.getConnection();

        //从连接中获取一个通道
        Channel channel = connection.createChannel();

        /*
            创建队列声明
                1.队列名
                2.是否是持久队列
                3.是否是排他队列(独占)
                4.是否自动删除
                5.其他参数属性设置
         */
        channel.queueDeclare(CommonUtil.QUEUE_SIMPLE, false, false, true, null);

        //定义消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String msg = new String(body, StandardCharsets.UTF_8);
                log.info("消费者收到消息:{}", msg);
                ThreadUtil.sleep(1, TimeUnit.SECONDS);
            }
        };
        channel.basicConsume(CommonUtil.QUEUE_SIMPLE, true, consumer);
    }

}
